package com.fate.system.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fate.framework.dto.IdParamDTO;
import com.fate.framework.exception.KKException;
import com.fate.framework.utils.CommonUtil;
import com.fate.framework.utils.SystemUtil;
import com.fate.framework.vo.LabelValueVO;
import com.fate.system.dto.user.UserAddDTO;
import com.fate.system.dto.user.UserPageDTO;
import com.fate.system.dto.user.UserUpdateDTO;
import com.fate.system.entity.User;
import com.fate.system.service.IDictService;
import com.fate.system.service.IRoleService;
import com.fate.system.service.IUserService;
import com.fate.system.vo.user.UserDetailVO;
import com.fate.system.vo.user.UserListVO;
import com.fate.system.vo.user.UserSelfVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "用户操作 API")
@RestController
@RequestMapping("/api/v1.0/user")
public class UserController {

  @Resource private IUserService userService;
  @Resource private IDictService dictService;
  @Resource private IRoleService roleService;

  @SaCheckRole("super_admin")
  @Operation(summary = "新增")
  @PostMapping("/add")
  public void add(@RequestBody @Valid UserAddDTO addDTO) {
    User user = SystemUtil.buildResource(addDTO, User.class);
    userService.save(user);
  }

  @SaCheckRole("super_admin")
  @Operation(summary = "删除")
  @PostMapping("/remove")
  public void remove(@RequestBody @Valid IdParamDTO idParamDTO) {
    String id = idParamDTO.getId();

    userService.removeUser(id);
  }

  @SaCheckRole("super_admin")
  @Operation(summary = "更新")
  @PostMapping("/update")
  public void update(@RequestBody @Valid UserUpdateDTO updateDTO) {
    String id = updateDTO.getId();
    String loginId = (String) StpUtil.getLoginId();
    if (!Objects.equals(id, loginId)) {
      throw new KKException("不能修改其他人的信息");
    }
    User user = SystemUtil.buildResource(updateDTO, User.class);
    userService.updateById(user);
  }

  @SaCheckRole("super_admin")
  @Operation(summary = "详情")
  @PostMapping("/detail")
  public UserDetailVO detail(@RequestBody @Valid IdParamDTO idParamDTO) {
    return getUserInfo(idParamDTO.getId());
  }

  @SaCheckRole("super_admin")
  @Operation(summary = "分页列表")
  @PostMapping("/getPageList")
  public Page<UserListVO> getPageList(@RequestBody @Valid UserPageDTO pageDTO) {
    Page<User> page = userService.getPageList(pageDTO);
    Page<UserListVO> buildResource = SystemUtil.buildResource(page, UserListVO.class);
    if (CommonUtil.isNullOrEmpty(buildResource.getRecords())) {
      return buildResource;
    }
    dictService.transfer(buildResource);
    List<String> roleIds =
        buildResource.getRecords().stream()
            .map(UserListVO::getRoleIds)
            .flatMap(List::stream) // 拍平
            .distinct() // 去重
            .toList();

    if (CommonUtil.notNullOrEmpty(roleIds)) {
      Map<String, String> roleId2RoleNameMap = roleService.roleId2RoleNameMap(roleIds);
      if (CommonUtil.notNullOrEmpty(roleId2RoleNameMap)) {
        buildResource
            .getRecords()
            .forEach(
                userListVO -> {
                  List<String> roleNames = new ArrayList<>();
                  userListVO
                      .getRoleIds()
                      .forEach(
                          roleId -> {
                            if (roleId2RoleNameMap.containsKey(roleId)) {
                              roleNames.add(roleId2RoleNameMap.get(roleId));
                            }
                          });
                  userListVO.setRoleNames(roleNames);
                });
      }
    }

    return buildResource;
  }

  @SaCheckRole("super_admin")
  @Operation(summary = "获取用户列表")
  @PostMapping("/getUserList")
  public List<LabelValueVO> getUserList() {
    List<User> userList = userService.list();
    if (CommonUtil.isNullOrEmpty(userList)) {
      return new ArrayList<>();
    }

    return userList.stream().map(i -> new LabelValueVO(i.getNickname(), i.getId())).toList();
  }

  @PostMapping("/selfInfo")
  public UserSelfVO selfInfo() {
    String loginId = (String) StpUtil.getLoginId();
    return SystemUtil.buildResource(getUserInfo(loginId), UserSelfVO.class);
  }

  /**
   * 获取用户详情
   *
   * @param loginId 用户id
   * @return 用户信息
   */
  private UserDetailVO getUserInfo(String loginId) {
    User user = userService.getById(loginId);
    if (CommonUtil.isNullOrEmpty(user)) {
      throw new KKException("用户不存在");
    }

    UserDetailVO userDetailVO = SystemUtil.buildResource(user, UserDetailVO.class);
    dictService.transfer(userDetailVO);

    // 获取用户角色ids
    List<String> roleIds = user.getRoleIds();

    // 用户角色翻译
    List<String> roleNames = roleService.getRoleNameByIds(roleIds);
    userDetailVO.setRoleNames(roleNames);

    return userDetailVO;
  }
}
